package com.example.udpmulticastdemo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.*;

/**
 * UDP单播发送端
 */
public class UDPSingleCast {
    private static long mSortNum=0;
    private static boolean mIsRunning=false;
    public static void start(String ip,int port){
        mIsRunning=true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 创建发送者Socket对象
                DatagramSocket sender = null;
                try {
                    sender = new DatagramSocket();

                    InetAddress receiverIP = InetAddress.getByName(ip); // 接收者的IP地址
                    int receiverPort = port; // 接收者的端口号

                    while(mIsRunning) {
                        String message = (mSortNum++) + " Hello, World!";
                        byte[] sendData = message.getBytes("UTF-8");
                        // 构造数据包并发送到指定的目标主机和端口
                        DatagramPacket packet = new DatagramPacket(sendData, sendData.length, receiverIP, receiverPort);
                        sender.send(packet);

                        System.out.println("消息已成功发送！");
                    }

                    // 关闭发送者Socket连接
                    sender.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    public static void stop(){
        mIsRunning=false;
    }
}